<template>
  <el-form
    ref="form"
    :model="form"
    :rules="rules"
    autocomplete="on"
    label-position="right"
    label-width="95px"
  >
    <div v-for="item in cols" :key="item.colName">
      <el-form-item
        v-if="!(item.colName==='id' && editType==='add') && item.hiddenIn !== editType"
        :label="item.displayName"
        :prop="item.colName"
      >
        <!-- 选择 -->
        <el-select
          v-if="item.dataType==='select'"
          v-model="form[item.colName]"
          :readonly="item.readOnly||readonly"
        >
          <el-option
            v-for="opt in item.data.options"
            :key="opt.value"
            :label="opt.name"
            :value="opt.value"
          />
        </el-select>
        <!-- 默认 -->
        <el-input
          v-else
          v-model="form[item.colName]"
          :readonly="item.readOnly||readonly"
          :type="item.dataType"
        />
      </el-form-item>
    </div>
    <el-form-item>
      <el-button v-if="!readonly" type="primary" @click="onSubmit">确定</el-button>
      <el-button @click="onCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'UserEdit',
  props: {
    values: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      form: {},
      readonly: false,
      rules: {
        'userName': [{ required: true, message: '不能为空' }],
        'gender': [{ required: true, message: '不能为空' }],
        'email': [{ required: true, type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }],
        'telNumber': [{ required: true, message: '不能为空' }]
      },
      editType: 'edit',
      cols: [
        // { displayName: 'ID', colName: 'id', readOnly: true },
        { displayName: '显示昵称', colName: 'userName' },
        { displayName: '邮箱', colName: 'email' },
        { displayName: '性别', colName: 'gender', dataType: 'select', data: {
          options: [
            { name: '女', value: 0 },
            { name: '男', value: 1 },
            { name: '保密', value: 2 }
          ]
        }},
        { displayName: '手机号', colName: 'telNumber' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'name',
      'avatar',
      'roles'
    ])
  },
  watch: {
    values(newValues) {
      this.form = Object.assign({}, newValues)
    }
  },
  created() {
  },
  mounted() {
    this.form = Object.assign({}, this.values)
  },
  methods: {
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$emit('onSubmit', this.form)
        } else {
          console.log('error validate', this.form)
          this.$message.error('表单内有错误，请检查修改后再提交！')
        }
      })
    },
    onCancel() {
      this.$emit('onCancel')
    }
  }
}
</script>
<style scoped>
.line{
  text-align: center;
}
</style>
